//
//  SCGestureSetController.m
//  SCTouchDemo
//
//  Created by 小广 on 2016/12/20.
//  Copyright © 2016年 小广. All rights reserved.
//  手势设置/删除/修改页面

#import "SCGestureSetController.h"
#import "MYZGestureView.h"
#import "MYZCircleView.h"
#import "MYZGestureShapeView.h"
#import "CALayer+shake.h"
#import "SCSecureHelper.h"

NSString * const promptDefaultMessage =          @"绘制解锁图案";
NSString * const promptSetAgainMessage =         @"再次绘制解锁图案";
NSString * const promptSetAgainErrorMessage =    @"前后设置不一致";
NSString * const promptChangeGestureMessage =    @"请输入原手势密码";
NSString * const promptTestGestureMessage =    @"请输入手势密码";
NSString * const promptPointShortMessage =       @"连接至少4个点，请重新设置";
NSString * const promptPasswordErrorMessage =    @"手势密码错误";

#define MarginTop   25.0
#define Margin      8.0
#define ShapeWH     40.0
#define BottomHeight  44.0

@interface SCGestureSetController ()

/// 手势九宫格
@property (nonatomic, strong) MYZGestureView * gestureView;
@property (nonatomic, strong) UILabel * messageLabel;
@property (nonatomic, strong) UILabel * titleLabel;
@property (nonatomic, strong) UIImageView * backgroundImageView;
@property (nonatomic, strong) UIButton *forgetPasswordButton;


@property (nonatomic, copy) NSString *  firstGestureCode;
@property (nonatomic, copy) SCGestureSetBlock block;

@end

@implementation SCGestureSetController

- (instancetype)init {
    if (self = [super init]) {
        _gestureSetType = SCGestureSetTypeChange;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNav];
    [self setupSubViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}


#pragma mark - 布局UI
- (void)setupSubViews {
    // 针对和UIScrollView类无关控件的处理，这样设置坐标从(0,0)开始时,不会被导航条遮挡.
    [self.view addSubview:self.backgroundImageView];
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.messageLabel];
    [self setupGestureView];
    if(self.gestureSetType == SCGestureSetTypeTest)
    {
        self.messageLabel.text = promptTestGestureMessage;
        [self.view addSubview:self.forgetPasswordButton];
    }
    else if (self.gestureSetType == SCGestureSetTypeChange)
    {
        self.messageLabel.text = promptChangeGestureMessage;
        [self.view addSubview:self.forgetPasswordButton];
    }
    
}

- (void)setupNav {
//    self.title = @"设置手势密码";
//    if (self.gestureSetType == SCGestureSetTypeDelete) {
//        self.title = @"验证手势密码";
//    }
}


/// 手势九宫格
- (void)setupGestureView
{
    [self.view addSubview:self.gestureView];
    self.gestureView.showArrowDirection = NO;
    
    kWeakSelf
    [self.gestureView setGestureResult:^BOOL(NSString *gestureCode) {
        return [weakSelf gestureResult:gestureCode];
    }];
}

// 验证手势密码成功后，修改手势密码用到
- (void)resetTopViews {
    if (self.gestureSetType != SCGestureSetTypeChange) {
        return;
    }
    self.forgetPasswordButton.hidden = YES;
    self.gestureSetType = SCGestureSetTypeSetting;
    self.messageLabel.text = promptDefaultMessage;
    self.messageLabel.textColor = UIColorFromRGBA(0xffffff, 0.6);
}
#pragma mark - 懒加载

/// 手势九宫格
- (MYZGestureView *)gestureView {
    if (!_gestureView) {
        CGFloat gestureViewX = (ScreenWidth - GestureWH) * 0.5;
        CGFloat gestureViewY = self.messageLabel.bottom + 50;
        _gestureView = [[MYZGestureView alloc] initWithFrame:CGRectMake(gestureViewX, gestureViewY, GestureWH, GestureWH)];
    }
    return _gestureView;
}

- (UILabel *)messageLabel {
    if (!_messageLabel) {
        CGFloat labelY = self.titleLabel.bottom + 10;
        _messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, labelY, ScreenWidth, LabelHeight)];
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        _messageLabel.font = [UIFont systemFontOfSize:16.0];
        _messageLabel.textColor = UIColorFromRGBA(0xffffff, 0.6);
        _messageLabel.text = promptDefaultMessage;
    }
    return _messageLabel;
}
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        CGFloat labelY = 88 - 64;
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, labelY, ScreenWidth, LabelHeight)];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont systemFontOfSize:30.0];
        _titleLabel.textColor = UIColorFromRGBA(0xffffff, 0.6);
        _titleLabel.text = @"思萌";
    }
    return _titleLabel;
}

- (UIButton *)forgetPasswordButton
{
    if(!_forgetPasswordButton)
    {
        _forgetPasswordButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_forgetPasswordButton setTitle:@"忘记手势密码?" forState:UIControlStateNormal];
        [_forgetPasswordButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
        [_forgetPasswordButton.titleLabel setFont:kSystemFontSize(15)];
        
        [_forgetPasswordButton sizeToFit];
        _forgetPasswordButton.left = ScreenWidth/2 - _forgetPasswordButton.width/2;
        _forgetPasswordButton.bottom = ScreenHeight - 30 - 64;
        [_forgetPasswordButton addTarget:self action:@selector(forgetAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _forgetPasswordButton;
}

- (UIImageView *)backgroundImageView
{
    if(!_backgroundImageView)
    {
        _backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg"]];
        _backgroundImageView.frame = CGRectMake(0, -64, ScreenWidth, ScreenHeight);
    }
    return _backgroundImageView;
}


- (void)forgetAction
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"清除手势密码，重新登陆并设置。" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView showWithCompletionHandler:^(NSInteger buttonIndex) {
        if(buttonIndex == 1)
        {
            [SCSecureHelper openGesture:NO];
        }
    }];
}

#pragma mark - 对外方法
/// 设置手势完成的回调
- (void)gestureSetComplete:(SCGestureSetBlock)block {
    self.block = block;
}

#pragma mark - action事件
- (void)back {
    // 点击返回设置失败
    if (self.block) {
        self.block(NO);
    }
    [self popViewController];
}

- (void)bottomButtonAction:(UIButton *)sender {
    // 验证登录密码
}

#pragma mark - 对内方法
// 重设手势
- (void)resetGesture {
    [self.navigationItem.rightBarButtonItem setEnabled:NO];
    self.firstGestureCode = nil;
    self.messageLabel.text = promptDefaultMessage;
    self.messageLabel.textColor = [UIColor blackColor];
}

- (void)popViewController {
    [self leftBarButtonAction:nil];
}

// 手势密码结果的处理
- (BOOL)gestureResult:(NSString *)gestureCode {
    
    if (self.gestureSetType == SCGestureSetTypeSetting) {
        // 首次设置手势密码
        
        if (gestureCode.length >= 4) {
            if (!self.firstGestureCode) {
                self.firstGestureCode = gestureCode;
                self.messageLabel.text = promptSetAgainMessage;
                //导航栏上的重置按钮
                [self.navigationItem.rightBarButtonItem setEnabled:YES];
                
                return YES;
            } else if ([self.firstGestureCode isEqualToString:gestureCode]) {
                // 第二次绘制成功，返回上一页
                [SCSecureHelper saveGestureCodeKey:gestureCode];
                if (self.block) {
                    self.block(YES);
                }
                [self popViewController];
                return YES;
            }
        }
        // 点数少于4 或者 前后不一致
        if (gestureCode.length < 4 || self.firstGestureCode != nil) {
            // 点数少于4 或者 前后不一致
            self.messageLabel.text = gestureCode.length < 4 ? promptPointShortMessage : promptSetAgainErrorMessage;
            self.messageLabel.textColor = SCCircleErrorColor;
            [self.messageLabel.layer shake];
            return NO;
        }
        
    } else if (self.gestureSetType == SCGestureSetTypeDelete) {
        // 关闭手势密码
        if ([self verifyGestureCodeWitCode:gestureCode]) {
            //密码验证成功，回调关闭你手势密码
            [SCSecureHelper saveGestureCodeKey:nil];
            if (self.block) {
                self.block(YES);
            }
            [self popViewController];
            
            return YES;
        }
        return NO;
        
    } else if (self.gestureSetType == SCGestureSetTypeChange) {
        // 修改手势密码，修改前先验证原密码
        if ([self verifyGestureCodeWitCode:gestureCode]) {
            [self resetTopViews];
            return YES;
        }
        return NO;
    }
    else if (self.gestureSetType == SCGestureSetTypeTest)
    {
        //验证手势密码
        if ([self verifyGestureCodeWitCode:gestureCode]) {
            //密码验证成功，回调关闭你手势密码
            if (self.block) {
                self.block(YES);
            }
            [self popViewController];
            
            return YES;
        }
    }
    return NO;
}


// 验证原密码
- (BOOL)verifyGestureCodeWitCode:(NSString *)gestureCode {
    NSString * saveGestureCode = [SCSecureHelper gainGestureCodeKey];
    if ([gestureCode isEqualToString:saveGestureCode]) {
        return YES;
    } else {
        self.messageLabel.text =  promptPasswordErrorMessage;
        self.messageLabel.textColor = SCCircleErrorColor;
        [self.messageLabel.layer shake];
        return NO;
    }
}

- (void)dealloc {
    NSLog(@"%@===dealloc",NSStringFromClass([self class]));
}

@end
